package second.thread.threadlocaltest;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @Author: heweiwei
 * @Date: 3/16/25 PM4:30
 * @Description:
 */
public class InheritableThreadLocalTest {

    public static void main(String[] args) {
        test2();
    }


    public static void test1() {
        InheritableThreadLocal<String> threadLocal = new InheritableThreadLocal<>();
        threadLocal.set("hello world");
        System.out.println("main thread: " + threadLocal.get());


        new Thread(() -> {
            System.out.println("child thread before : " + threadLocal.get());
            threadLocal.set("world by child");
            System.out.println("child thread after : " + threadLocal.get());
        }).start();

        System.out.println("main thread: " + threadLocal.get());
    }

    public static void test2() {
        InheritableThreadLocal<String> threadLocal = new InheritableThreadLocal<>();
        threadLocal.set("hello world");
        System.out.println("main thread: " + threadLocal.get());

        ExecutorService executorService = Executors.newFixedThreadPool(1);
        executorService.execute(() -> {
            System.out.println("child thread get : " + threadLocal.get());
        });

        threadLocal.set("hello world after");
        System.out.println("main thread: " + threadLocal.get());

        executorService.execute(() -> {
            System.out.println("child thread get : " + threadLocal.get());
        });
    }
}
